package com.sudo.api.onload;

import com.sudo.common.component.ExtraProperties;
import com.sudo.common.enums.SysJobStatus;
import com.sudo.dao.admin.entity.SysMethodJob;
import com.sudo.dao.admin.entity.SysServerNodeJob;
import com.sudo.rpc.api.common.Constant;
import com.sudo.rpc.api.service.RmiSetServerService;
import com.sudo.rpc.api.utils.RegistryUtil;
import com.sudo.service.admin.config.CronTaskRegistry;
import com.sudo.service.admin.runnable.BeanMethodRunnable;
import com.sudo.service.admin.runnable.RpcMethodRunnable;
import com.sudo.service.admin.service.SysMethodJobService;
import com.sudo.service.admin.service.SysServerNodeJobService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.rmi.RemoteException;
import java.rmi.registry.Registry;
import java.util.List;

/**
 * @author 为道日损 2020-05-06 19:41
 * webSite：https://www.sudo.ren
 */
@Slf4j
@Component
public class OnloadSomething {
    @Resource
    private ExtraProperties extraProperties;

    @Resource
    private RmiSetServerService rmiSetServerService;

    @Resource
    private CronTaskRegistry cronTaskRegistry;

    @Resource
    private SysMethodJobService sysMethodJobService;

    @Resource
    private SysServerNodeJobService sysServerNodeJobService;

    /**
     * 初始化所有任务调度
     */
    @Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
    public void onLoadSysCronTask(){
        log.info("初始化任务调度");
        List<SysServerNodeJob> sysServerNodeJobList = sysServerNodeJobService.getSysServerNodeJobByStatus(SysJobStatus.RUN.name());
        sysServerNodeJobList.forEach(sysServerNodeJob -> {
            Runnable runnable = new RpcMethodRunnable(sysServerNodeJob);
            cronTaskRegistry.addCronTask(runnable, sysServerNodeJob.getCronExpression());
        });

        List<SysMethodJob> sysMethodJobList = sysMethodJobService.getSysMethodJobByStatus(SysJobStatus.RUN.name());
        sysMethodJobList.forEach(sysMethodJob -> {
            Runnable runnable = new BeanMethodRunnable(sysMethodJob);
            cronTaskRegistry.addCronTask(runnable, sysMethodJob.getCronExpression());
        });
    }

    public void onLoadRegistry() {
        //注册中心
        log.info("启动注册中心");
        int registryPort = extraProperties.getRegistryPort();
        RegistryUtil.startRegistry(registryPort);
        // 注册一个服务
        try {
            Registry registry = RegistryUtil.getRegistry(registryPort);
            registry.rebind(Constant.registryCenter, rmiSetServerService);
        } catch (RemoteException e) {
            log.error("启动注册中心异常：",e);
        }
    }
}
